package cn.jn.lhm.netty.part03;

import cn.hutool.core.util.StrUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/7/11 - 23:06
 **/
@Slf4j
public class Client {

    @SuppressWarnings("all")
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup client = new NioEventLoopGroup();
        ChannelFuture future = new Bootstrap()
                .group(client)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        Channel channel = future.sync().channel();

        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String text = scanner.nextLine();
                if (StrUtil.equals(text, "q")) {
                    // 这里的close也是异步处理的
                    channel.close();
                    log.info("关闭Socket链接");
                    break;
                }
                channel.writeAndFlush(text);
            }

        }, "sendMsg-Thread").start();

        ChannelFuture closeFuture = channel.closeFuture();

//        closeFuture.sync();
//        log.info("close channel over...");


        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("close channel over...");
                // 关闭连接
                client.shutdownGracefully();
            }
        });
    }
}
